<template>
	<view class="index">
		<CustomNavbar />
		<!-- 添加 scroll-y 属性启用垂直滚动 -->

		<scroll-view refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered"
			@scrolltolower="onScrolltolower" class="scroll-view" scroll-y="true" enhanced="true" show-scrollbar="false">
			<indexSkeleton v-if="isLoading" />
			<template v-else>
				<CirclePanel :circle-list="circleList" />
				<HotDigest ref="hotDigestRef" />
				<RecommendPost ref="recommendPostRef" />
			</template>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import CustomNavbar from '@/components/custom-navbar/CustomNavbar.vue'
	import CirclePanel from '@/components/circle-panel/CirclePanel.vue'
	import RecommendPost from '@/components/recommend/RecommendPost.vue'
	import HotDigest from '@/components/hot-digest/HotDigest.vue'
	import indexSkeleton from './components/indexSkeleton.vue'
	import type { CircleBasicInfo } from '@/api/circle/circle'
	import { getHotCircle } from '@/api/circle/circle'
	import { usePostStore } from '@/store/modules/post'
	import useUserStore from '@/store/modules/user'

	// 使用 Pinia store
	const postStore = usePostStore()

	const circleList = ref<CircleBasicInfo[]>([])

	const getCircleList = async () => {
		try {
			const res = await getHotCircle()
			circleList.value = res.data
		} catch (error) {
			console.error('获取圈子列表失败：', error)
		}
	}

	// 页面滚动到底部
	const recommendPostRef = ref(null)
	const hotDigestRef = ref(null)

	const isLoading = ref(true)

	// 数据下拉刷新状态
	const isTriggered = ref(false)

	// 页面触底
	const onScrolltolower = () => {
		recommendPostRef.value?.loadMore()
	}

	// 下拉刷新时出发刷新
	const onRefresherrefresh = async () => {
		// 开始刷新动画
		isTriggered.value = true
		// 刷新数据
		await Promise.all([
			postStore.fetchUserLikedPosts(), // 刷新用户点赞状态
			hotDigestRef.value?.refresh(), // 刷新热点文章
			recommendPostRef.value?.refresh(),
		])
		// 关闭刷新动画
		isTriggered.value = false
	}

	// 页面显示时的处理
	const onShow = async () => {
		// 从其他页面返回时，重新获取用户点赞状态
		await postStore.fetchUserLikedPosts()
	}

	// 在组件挂载时调用getCircleList
	onMounted(() => {
		isLoading.value = true
		getCircleList()
		useUserStore().getInfo()
		isLoading.value = false
	})

	// 添加页面生命周期
	uni.addInterceptor('navigateBack', {
		success() {
			// 页面返回时更新点赞状态
			postStore.fetchUserLikedPosts()
		}
	})
</script>

<style lang="scss">
	page {
		background-color: #f7f7f7;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.index {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.scroll-view {
		flex: 1;
		height: 0;
		/* 重要：配合flex使用时需要设置 */
	}
</style>